var baiduLocation;
var WAITER, TRADES, PRICE;
var $date, $time;
// 获取服务员个人信息
var getWaiter = function (id, callback) {
    api.ajax({
        url : SERVER_URL + '/entity/waiter/' + id,
        method : 'get',
        timeout: 30,
        dataType : 'json',
        cache : false
    }, callback);
};
// 获取工种信息
var getTrades = function (callback) {
    api.ajax({
        url : SERVER_URL + '/entity/config/trades',
        method : 'get',
        timeout: 30,
        dataType : 'json',
        cache : false
    }, callback);
};
// 生成订单
var postOrder = function (callback) {
    api.ajax({
        url : SERVER_URL + '/entity/order?token=' + TOKEN,
        method : 'post',
        timeout: 30,
        dataType : 'json',
        data : {
            values : {
                waiter: WAITER.phone,
                trades: api.pageParam.trades,
                price: PRICE,
                reserveTime: $date.value + ' ' + $time.value
            }
        },
        cache : false
    }, callback);
};
// 渲染服务员信息
var renderWaiter = function () {
    if (!WAITER) {
        return;
    }

    var $waiterInfo = $api.dom('#waiter_info');
    $waiterInfo.innerHTML = '';
    // photo
    $api.append($waiterInfo, '<img class="photo fr" src="' + SERVER_URL + '/entity/file/' + WAITER.photo + '">');
    // name
    $api.append($waiterInfo, '<div class="field">姓名：' + WAITER.name + '</div>');
    // sex
    $api.append($waiterInfo, '<div class="field">性别：' + WAITER.sex + '</div>');
    // trades
    $api.append($waiterInfo, '<div class="field">工种：' + WAITER.trades.join(',') + '</div>');
    // hometown
    $api.append($waiterInfo, '<div class="field">籍贯：' + WAITER.hometown + '</div>');
    // ageLevel
    $api.append($waiterInfo, '<div class="field">年龄：' + WAITER.ageLevel + '</div>');
    // empiricLevel
    $api.append($waiterInfo, '<div class="field">经验：' + WAITER.empiricLevel + '</div>');
    // eduLevel
    $api.append($waiterInfo, '<div class="field">学历：' + WAITER.eduLevel + '</div>');

};
// 渲染工种信息
var renderTrades = function() {
    if (!TRADES) {
        return;
    }

    var $tradesInfo = $api.dom('#trades_info');
    $tradesInfo.innerHTML = '';
    var trades = api.pageParam.trades;
    TRADES.some(function(item, i) {
        if (item.name == trades) {
            item.price.some(function(priceItme, j) {
                var $dom = $api.append($tradesInfo,
                    '<div class="classify">' +
                    '   <div class="info">' +
                    '       <div class="title">' + priceItme.name + '</div>' +
                    '       <div class="subtitle">' + priceItme.money + '元/' + priceItme.time + '分钟</div>' +
                    '   </div>' +
                    '   <button type="button" class="arrow confirm" onclick="openOrderCreate(\'' + priceItme.name + '\')">下单</button>' +
                    '</div>');
            });
            return true;
        }
    });
};
// 打开订单创建页面
var openOrderCreate = function (price) {
    var trades = api.pageParam.trades;
    TRADES.some(function(item, i) {
        if (item.name == trades) {
            item.price.some(function(priceItme, j) {
                if (priceItme.name == price) {
                    PRICE = priceItme;
                }
            });
        }
    });
    // 检查是否已经登录
    api.getPrefs({
        key: 'token'
    }, function(ret, err) {
        TOKEN = ret.value;
        if (TOKEN.length > 0) {
            var delay = 0;

            if ("ios" != api.systemType) {
                delay = 300;
            }
            postOrder(function(result, err) {
                if (result) {
                    api.closeWin({
                        name : 'waiters'
                    });
                    openOrder(result);
                    api.closeWin();
                } else {
                    api.alert({msg: '服务端错误。' + JSON.stringify(err)});
                }
            });
        } else {
            openLogin('waiterinfo');
        }
    });
}
var loginBack = function() {
    openOrderCreate(PRICE.name);
};
var openOrder = function(order) {

	var delay = 0;

	if ("ios" != api.systemType) {
		delay = 300;
	}

	api.openWin({
		name: "orderinfo",
		url: "./order_info.html",
		pageParam: {
            order: order
		},
		bounces: false,
		vScrollBarEnabled: false,
		hScrollBarEnabled: false,
		reload: true,
		delay: delay
	});
};
// 页面加载完成
var apiready = function() {
    baiduLocation = api.require('baiduLocation');
    $date = $api.dom('#reserve_date');
    $time = $api.dom('#reserve_time');
    /* 一个获取导航栏高度的方法. */
    window.getNavHeight = function() {
        var h = 44;

        if ("ios" == api.systemType && parseInt(api.systemVersion) >= 7) {
            h = 64;
        }
        return h;
    }

    /* 一个关闭窗口,返回上一级页面的优雅实现. */
    window.closeWin = function(winName) {
        api.closeWin();
    }

    // -----------------------------------------
    /* 导航栏自适应iOS 7. */
    var header = $api.byId('header');
    $api.fixIos7Bar(header);

    /* Android,点击返回键,可以返回上一级. */
    window.addEventListener("keyback", function() {
        window.addEventListener("keyback", function() {
            if (!api["pageParam"]["isFrame"]) { // 仅在是主窗口时,才捕捉 keyback事件.
                window.closeWin();
            }
        });
    });

    var waiterId = api.pageParam.id;
    getWaiter(waiterId, function(waiter, err) {
        if (waiter) {
            WAITER = waiter;
            renderWaiter();
            getTrades(function (result, err) {
                if (result) {
                    TRADES = result.values;
                    renderTrades();
                } else {
                    api.alert({msg: '服务端错误。' + err.msg});
                }
            });
        } else {
            api.alert({msg: '服务端错误。' + err.msg});
        }
    });

};
